import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';

import '../../themes/appTheme.dart';

// ignore: must_be_immutable
class NewOrEditFolderDialog extends StatefulWidget {
  NewOrEditFolderDialog({
    Key? key,
    required this.title,
    required this.message,
    required this.type,
  }) : super(key: key);

  String title;
  String message;
  String type;

  @override
  State<NewOrEditFolderDialog> createState() => _NewOrEditFolderDialogState();
}

class _NewOrEditFolderDialogState extends State<NewOrEditFolderDialog> {
  final folderNameController = TextEditingController();
  final BooksController _bookController = Get.find();
  bool isTeacher = false;
  final box = Hive.box('appconfig');

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    super.initState();
  }

  void _createFolder() async {
    try {
      int index = _bookController.bookFolders.indexWhere(
          (element) => element.folderName == folderNameController.text.trim());
      if (index != -1) {
        showSnackMsg(isTeacher
            ? 'Same lesson plan found, please check!'
            : 'Same folder name found, please check!');
        // Get.snackbar('Message'.tr, isTeacher ?'Same lesson plan found, please check!'.tr : 'Same folder name found, please check!'.tr,
        //     backgroundColor: Get.theme.primaryColor,
        //     colorText: Get.theme.primaryColorLight,
        //     snackPosition: SnackPosition.BOTTOM);
      } else {
        _bookController
            .createBookLibraryFolder(folderNameController.text)
            .then((data) {
          if (data.message != null && data.status == 1000) {
            showSnackMsg(isTeacher
                ? 'Lesson plan has been created!'
                : 'Folder has been created!');
            Navigator.of(context).pop();
          } else {
            showSnackMsg(isTeacher
                ? 'Error to create lesson plan'
                : 'Error to create folder');
          }
        });
      }
    } catch (error) {
      showSnackMsg(
          isTeacher ? 'Error to create lesson plan' : 'Error to create folder');
    } finally {
      EasyLoading.dismiss();
    }
  }

  void _editFolder() async {
    Log.debug(_bookController.getCurrentBookFolder().id);
    String? folderId = _bookController.getCurrentBookFolder().id;
    try {
      _bookController
          .updateLibraryFolderName(folderId!, folderNameController.text)
          .then((data) {
        if (data.message != null && data.status == 1000) {
          showSnackMsg(isTeacher
              ? 'Lesson plan updated successfully'
              : 'Folder updated successfully');
          // Get.snackbar(
          //     'Message'.tr,
          //     isTeacher
          //         ? 'Lesson plan updated successfully'.tr
          //         : 'Folder updated successfully'.tr,
          //     backgroundColor: Get.theme.primaryColor,
          //     colorText: Get.theme.primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
          Navigator.of(context).pop();
        } else {
          showSnackMsg(isTeacher
              ? 'Error to update lesson plan'
              : 'Error to update folder');
          // Get.snackbar(
          //     'Message'.tr,
          //     isTeacher
          //         ? 'Error to update lesson plan'.tr
          //         : 'Error to update folder'.tr,
          //     backgroundColor: Get.theme.primaryColor,
          //     colorText: Get.theme.primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        }
      });
    } catch (error) {
      showSnackMsg(
          isTeacher ? 'Error to update lesson plan' : 'Error to update folder');
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    if (this.widget.type == 'edit')
      folderNameController.text =
          _bookController.getCurrentBookFolder().folderName ?? 'name';

    return AlertDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            this.widget.title,
            style: TextStyle(
                fontSize: 30.0,
                decoration: TextDecoration.underline,
                decorationStyle: TextDecorationStyle.dotted),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Icon(Icons.cancel,
                color: Get.isDarkMode ? Colors.white : Colors.blueGrey),
          ),
        ],
      ),
      titleTextStyle: TextStyle(
          letterSpacing: 1,
          color: Get.isDarkMode ? Get.theme.primaryColorDark : Colors.blueGrey,
          fontSize: 21),
      backgroundColor:
          Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(6.0),
        ),
      ),
      content: Container(
        height: 300,
        width: 450,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                  child: Container(
                    width: 300,
                    child: TextField(
                      controller: folderNameController,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(9.0)),
                        hintStyle: TextStyle(
                          color: Get.isDarkMode
                              ? Get.theme.primaryColorLight
                              : Colors.grey[300],
                        ),
                        hintText: 'Folder Name'.tr,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Center(
              child: Container(
                width: 210.0,
                height: 45.0,
                child: DebouncedMaterialButton(
                    debounceTimeMs: 1800,
                    color: Get.isDarkMode
                        ? Theme.of(context).primaryColorDark
                        : Theme.of(context).primaryColor,
                    textColor: Get.isDarkMode
                        ? (Colors.black)
                        : Theme.of(context).primaryColorLight,
                    onPressed: () {
                      if (widget.type == 'edit') {
                        _editFolder();
                      } else {
                        _createFolder();
                      }
                    },
                    child: Text(
                      'Submit'.tr,
                      style: TextStyle(fontSize: 18.0),
                    )),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
